package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.mapper.RoleMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class CrmRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("======================================");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        //获取主体的身份信息
        Employee employee = (Employee) subject.getPrincipal();
        System.out.println(employee);
        //判断是否超级管理员
        if (employee.isAdmin()) {
            info.addRole("ADMIN");//方便后续判断是否管理员可以直接用submit来判断
            info.addStringPermission("*:*");
        } else {
            //根据用户的id查询该用户拥有的角色编码
            List<Role> roles = roleMapper.selectByEmpId(employee.getId());
            ArrayList<String> roleSnList = new ArrayList<>();
            for (Role role : roles) {
                roleSnList.add(role.getSn());//放入角色编码
            }
            info.addRoles(roleSnList);
            //根据用户的id查询该用户的权限表达式
            List<String> permissions = permissionMapper.selectByEmpId(employee.getId());
            info.addStringPermissions(permissions);
        }


        //当前登录用户所有的角色(假数据)
//        info.addRoles(Arrays.asList("HR_MSG","admin"));
//        info.addStringPermissions(Arrays.asList("employee:update","employee:delete"));
        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //通过token获取用户名（用户登录填的）
        Object username = token.getPrincipal();
        //判断是否存在数据库（假数据）
        Employee employee = employeeMapper.selectByName((String) username);
        if (employee != null) {
            System.out.println(this.getName());
            //身份信息，凭证信息（正确）,盐,当前realm的名字
            return new SimpleAuthenticationInfo(employee,employee.getPassword(),
                    ByteSource.Util.bytes(username),this.getName());
        }
        //返回值就是查询出来的数据，如果查到这个账号，就应该返回该账号的正确的数据,如果查不到，就返回null
        return null;
    }
}
